package com.java.servlet.web.roles.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.java.servlet.web.commons.CatalogoComunVo;
import com.java.servlet.web.commons.PropertiesUtils;
import com.java.servlet.web.roles.service.RolesService;
import com.java.servlet.web.roles.service.RolesServiceImpl;
import com.java.servlet.web.roles.vo.RolesVo;

/**
 * Servlet implementation class RolesController
 */
@WebServlet (name = "RolesController", urlPatterns = "/roles/rolesController")
public class RolesController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(RolesController.class);
	private static final int INIT_ROLES = 1;
	private static final int EDITAR_ROL = 2;
	private static final int GUARDAR_EDIT_ROL = 3;
	private static final int NUEVO_ROL = 4;
	private static final int GUARDAR_NUEVO_ROL = 5;
	private static final int ELIMINAR_ROL = 6;
	private Properties viewConfig;
	private Properties fieldConfig;
    protected RolesService rolesService;
	private RolesVo rolesVo = null;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RolesController() {
    }
    public void init() {
		try {
			super.init();
			rolesService = new RolesServiceImpl();
			viewConfig = PropertiesUtils.getPropertiesFromFile(getServletContext().getResource("/WEB-INF/view-config.properties"));
			fieldConfig = PropertiesUtils.getPropertiesFromFile(getServletContext().getResource("/WEB-INF/form-config.properties"));
		} catch (MalformedURLException ex) {
			log.info("Error fatal, no se puedo cargar el archivo de configuracion de vistas." + ex);
		} catch(ServletException serEx){
			log.info("Error fatal, no se puedo cargar el archivo de configuracion de vistas." + serEx);
		}
    }
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
		int metodo = Integer.parseInt(request.getParameter("method"));
		RequestDispatcher dispatcher = null;
		HttpSession sessionApp = request.getSession(true);
		boolean session = (Boolean) ((Boolean) sessionApp.getAttribute("auth") != null ?sessionApp.getAttribute("auth"):false);
		try {
			if(session){
				switch (metodo) {
				case INIT_ROLES:
					rolesVo = new RolesVo();
					List<RolesVo> getListaRoles = rolesService.getListaRoles(rolesVo);
					request.setAttribute("getListaRoles", getListaRoles);
					dispatcher = request.getRequestDispatcher(viewConfig.getProperty("init.roles"));
					dispatcher.forward(request, response);
					break;
				case EDITAR_ROL:
					rolesVo = new RolesVo();
					int idRol = Integer.parseInt(request.getParameter("idRol"));
					rolesVo.setIdRol(idRol);
					RolesVo rolVo = rolesService.getRol(rolesVo);
					request.setAttribute("rolVo", rolVo);
					request.setAttribute("listVigencia", getCatVigencia());
					dispatcher = request.getRequestDispatcher(viewConfig.getProperty("editar.roles"));
					dispatcher.forward(request, response);
				break;
				case GUARDAR_EDIT_ROL:
					rolesService.guardarEditRol(getRolEditFromRequest(request));
					dispatcher = request.getRequestDispatcher(viewConfig.getProperty("control.init.roles"));
					dispatcher.forward(request, response);
				break;
				case NUEVO_ROL:
					request.setAttribute("listVigencia", getCatVigencia());
					dispatcher = request.getRequestDispatcher(viewConfig.getProperty("nuevo.roles"));
					dispatcher.forward(request, response);
				break;
				case GUARDAR_NUEVO_ROL:
					rolesService.guardarNuevoRol(getRolNewFromRequest(request));
					dispatcher = request.getRequestDispatcher(viewConfig.getProperty("control.init.roles"));
					dispatcher.forward(request, response);
				break;
				case ELIMINAR_ROL:
					rolesVo = new RolesVo();
					int idRolEliminar = Integer.parseInt(request.getParameter("idRol"));
					rolesVo.setIdRol(idRolEliminar);
					rolesService.borrarRol(rolesVo);
					dispatcher = request.getRequestDispatcher(viewConfig.getProperty("control.init.roles"));
					dispatcher.forward(request, response);
				break;
				}
			} else {
				System.out.println("session.no.existe-----[roles}-------------------");
				dispatcher = request.getRequestDispatcher(viewConfig.getProperty("session.no.existe"));
				dispatcher.forward(request, response);
			}
		} catch (Exception e) {
            request.setAttribute("ex", e);
            dispatcher = request.getRequestDispatcher(viewConfig.getProperty("error"));
            dispatcher.forward(request, response);
			System.out.println("Error en LoginController " + e);
			e.printStackTrace();
		} finally {
            out.close();
        }
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
    private RolesVo getRolNewFromRequest(HttpServletRequest request) {
    	RolesVo rol = new RolesVo();
 
            if (StringUtils.isNotBlank(request.getParameter(fieldConfig.getProperty("form.rol.descripcion")))) {
                rol.setDescRol(request.getParameter(fieldConfig.getProperty("form.rol.descripcion")));
            } 
            if (StringUtils.isNotBlank(request.getParameter(fieldConfig.getProperty("form.rol.idvigencia")))) {
            	rol.setIdVigencia(request.getParameter(fieldConfig.getProperty("form.rol.idvigencia")));
            } 
        return rol;
    }
    private RolesVo getRolEditFromRequest(HttpServletRequest request) {
    	RolesVo rol = new RolesVo();
    		rol.setIdRol(Integer.parseInt(request.getParameter(fieldConfig.getProperty("form.rol.idrol"))));
            if (StringUtils.isNotBlank(request.getParameter(fieldConfig.getProperty("form.rol.descripcion")))) {
                rol.setDescRol(request.getParameter(fieldConfig.getProperty("form.rol.descripcion")));
            } 
            if (StringUtils.isNotBlank(request.getParameter(fieldConfig.getProperty("form.rol.idvigencia")))) {
            	rol.setIdVigencia(request.getParameter(fieldConfig.getProperty("form.rol.idvigencia")));
            } 
        return rol;
    }
	private List<CatalogoComunVo> getCatVigencia(){
		CatalogoComunVo catalogoComunVo = null;
		List<CatalogoComunVo> listaVigencia = new ArrayList<CatalogoComunVo>();
		
		catalogoComunVo = new CatalogoComunVo();
		catalogoComunVo.setIdValorCad("S");
		catalogoComunVo.setDescValor("SI");
		listaVigencia.add(catalogoComunVo);
		
		catalogoComunVo = new CatalogoComunVo();
		catalogoComunVo.setIdValorCad("N");
		catalogoComunVo.setDescValor("NO");
		listaVigencia.add(catalogoComunVo);
		
		return listaVigencia;
	}

}
